<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/2
 * Time: 10:36
 */

namespace app\api\controller;


use app\common\logic\MyPackage;
use app\common\model\DrawRecord;
use app\common\model\GiftRecord;
use app\common\model\MyCar;
use app\common\model\Room;
use app\common\model\RoomBackground;
use app\common\model\RoomBlacklist;
use app\common\model\RoomHistory;
use app\common\model\RoomLog;
use app\common\model\UserGuard;
use app\common\model\Users;
use app\common\service\ChatService;
use app\common\service\DrawService;
use think\Db;
use think\Exception;
use think\Request;

class Play extends User
{

    /**
     * 房间列表
     */
    public function roomList()
    {
        $map['a.status'] = 1;
//        $map['a.is_order'] = 1;
        $map['top'] = 0;
        $map['is_close'] = 0;
        $type = input('post.type');
        if (is_numeric($type)) $map['a.type'] = $type;
        $model = new Room();
        $rows = $model->getRows($map);
        api_return(1,'获取成功',$rows);
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 热门房间
     */
    public function hot()
    {
        $model = new Room();
        $map['a.status'] = 1;
        $map['a.is_order'] = 1;
        $rows = $model->getHot($map);
        api_return(1,'获取成功',$rows);
    }

    /**
     * 推荐房间
     */
    public function top()
    {
        $model = new Room();
        $map['a.status']   = 1;
        $map['a.top']   = 1;
//        $map['a.is_order'] = 1;
        $rows = $model->getTop($map,$this->user_id);
        api_return(1,'获取成功',$rows);
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 房间搜索
     */
    public function roomSearch()
    {
        $room_name = input('post.room_name');
        if (!empty($room_name)){
            $map['a.room_name|room_id|show_id'] = ['like','%'.$room_name.'%'];
        }

        if (is_numeric(input('cid'))){
            $map['c.cid'] = input('cid');
        }

        $map['a.status'] = 1;
        $model = new Room();
        $rows = $model->_list($map,$this->user_id);
        api_return(1,'搜索成功',$rows);
    }

    /**
     * 进入房间
     */
    public function joinRoom()
    {

        $this->ApiLimit(1,$this->user_id);

        $data = input('post.');
        $model = new Room();

        $data = $model->joinRoom($data['room_id'],$this->user_id,trim($data['password']));

        if ($data !== false) {

            //查询用户是否有装备坐骑
            $map1['end_time'] = [['>',time()],['=',0],'or'];
            $map1['user_id']  = $this->user_id;
            $map1['status']   = 1;
            $map1['is_use']   = 1;

            $car_id = MyCar::where($map1)->cache(3)->value('car_id');

            if ($car_id > 0){

                //通知房间谁驾驶座驾进入了
                $array['user_id'] = hashid($this->user_id);
                $array['nick_name'] =$this->userInfo('nick_name');
                $array['uuid'] = $this->userInfo('uuid');
                $array['header_img'] = $this->userInfo('header_img');
                $array['carInfo'] = (\app\common\model\Car::field('thumbnail,img,car_id')->find($car_id))->getData();
                $this->sendRoomMsg($data['room_id'],'carIn',$array);
            }

            //加入一个房间前先执行退出房间操作
            $lastRoom = Db::name('user_extend')->where('user_id',$this->user_id)->value('room_id');

            if ($lastRoom != $data['room_id']){
                $refresh = self::outRoomFunc($this->user_id,$lastRoom);
                if ($refresh){
                    $this->refreshWheat($lastRoom);
                }
            }

            $chat = cache('chat'.$data['room_id']);

            //判断是否开启公屏
            if ($chat == 'close'){
                $data['chat'] = 0;
            }else{
                $data['chat'] = 1;
            }

            //贵族加入房间增加热度房间
            $noble_id = self::checkNoble($this->userExtra('user_id,noble_id,noble_time'));
            if ($noble_id == 5 || $noble_id == 4 || $noble_id == 3 ){
                if ($noble_id == 5){
                    $hot = 1001;
                }elseif ($noble_id == 4){
                    $hot = 501;
                }else{
                    $hot = 201;
                }

            }else{
                $hot = 1;
            }
            //增加房间热度
            addHot($data['room_id'],$hot);
            $data['noble_id'] = $noble_id;
            $data['level'] = $this->userExtra('level');
            //查询当前用户是否被禁言

            $map['room_id']  = $data['room_id'];
            $map['user_id']  = $this->user_id;
            $map['status']   = 1;
            $map['end_time'] = ['>',time()];

            $data['baned'] = Db::name('room_baned')->where($map)->value('id')?true:false;
            //修改当前用户所在房间
            Db::name('user_extend')->where('user_id',$this->user_id)->update(['room_id'=>$data['room_id']]);

            //房间热度
            $data['hot'] = hotValue($data['room_id']);

            $onlineUser = Db::name('user_extend')->where('room_id',$data['room_id'])->cache(3)->count();

            //通知到房间热度修改
            $this->sendRoomMsg($data['room_id'],'hotChange',['hot'=>$data['hot'],'onlineUser'=>$onlineUser]);

            //写入房间观看记录
            $room_id = $data['room_id'];
            $user_id = $this->user_id;
            $history = db('room_history')->where(['room_id'=>$room_id,'user_id'=>$user_id])->find();
            if($history){
                db('room_history')->where(['room_id'=>$room_id,'user_id'=>$user_id])->update(['update_time'=>time()]);
            }else{
                $his['room_id'] = $room_id;
                $his['user_id'] = $user_id;
                $his['status'] = 1;
                $his['create_time'] = time();
                $his['update_time'] = time();
                db('room_history')->insert($his);
            }

//            //查询当前用户是否被禁言
//            $map['room_id']  = $data['room_id'];
//            $map['user_id']  = $this->user_id;
//            $map['status']   = 1;
//            $map['end_time'] = ['>',time()];
//
//            $data['baned'] = Db::name('room_baned')->where($map)->value('id')?true:false;
//            //修改当前用户所在房间
//            Db::name('user_extend')->where('user_id',$this->user_id)->update(['room_id'=>$data['room_id']]);

            api_return(1,'获取成功',$data);
        }
        api_return(0,$model->getError());
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 退出房间
     */
    public function outRoom()
    {
        $room_id = input('post.room_id');
        $data['room_id'] = 0;
        self::updateUserExtend($this->user_id,$data);
        //用户上麦成功 且在排麦中 清除排麦数据
        self::outRoomFunc($this->user_id,$room_id);
        self::refreshWheat($room_id);
        api_return(1,'退出房间成功');
    }



    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 房间在线用户列表
     */
    public function onlineUser()
    {
        $map = [];
        $id  = input('post.room_id');

        if (!is_numeric($id)) api_return(0,'请输入房间id');
        $online = ChatService::getInstance()->chatroom()->queryUser($id, '500', '2');

        $array  = json_decode($online,true);
        $rows = [];

        if ($array['code'] == 200 && $array['total'] >=1){
            $users = [];
            foreach ($array['users'] as $k => $v){

                $users[] = dehashid($v['id']);

            }
            $users = implode(',',$users);
            $map = [];
            $map['a.user_id'] = ['in',$users];
//            $map['e.room_id']       = $id;
//            $map['e.online_status'] = 1;
            $model = new Users();

            $rows = $model->getItems($map);

        }
        api_return(1,'获取成功',$rows);
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 房间日志
     */
    public function roomLog()
    {
        $map['room_id'] = input('post.room_id');

        if (!is_numeric($map['room_id'])) api_return(0,'房间id错误');

        $model = new RoomLog();

        $rows  = $model->getRows($map);

        api_return(1,'获取成功',$rows);
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 房间黑名单列表
     */
    public function blackList()
    {
        $map['a.room_id'] = input('post.room_id');
        if (!is_numeric($map['a.room_id'])) api_return(0,'房间id错误');

        $map['a.status'] = 1;
        $map['a.end_time'] = ['>',time()];

        $model = new RoomBlacklist();

        $rows  = $model->getRows($map);

        api_return(1,'获取成功',$rows);

    }

    /**
     * 当前用户的观看历史
     */
    public function history(){

        $user_id = $this->user_id;
        $model = new RoomHistory();
        $result = $model->getHistoryList($user_id);
        if($result !== false){
            api_return(1,'成功',$result);
        }else{
            api_return(0,'暂无数据');
        }
    }



    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 房间打赏列表
     */
    public function roomGift()
    {

        $map['a.room_id'] = input('post.room_id');
        if (!is_numeric($map['a.room_id'])){
            api_return(0,'参数错误');
        }
        $map['a.status']  = 1;
        $model = new GiftRecord();

        $rows = $model->giftList($map);

        api_return(1,'获取成功',$rows);
    }


    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 真爱排行榜
     */
    public function trueLove()
    {

        $map['a.status'] = 1;
        $map['a.room_id'] = ['>',0];
        $map['g.price'] = ['>',519];
        $model = new GiftRecord();

        $rows = $model->getTrueLove($map);

        api_return(1,'获取成功',$rows);
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 守护排行榜
     */
    public function protect()
    {
        $map['a.status'] = 1;
        $map['a.room_id'] = ['>',0];
        $model = new GiftRecord();
        $rows = $model->protect($map);
        api_return(1,'获取成功',$rows);
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 获取CP排行榜
     */
    public function guard()
    {
        $time = cache('guardTime');
        $map = [];

        if (time()+86430 > $time){
            $time = time() + 86430;
            cache('guardTime',$time);
        }

        $map['a.status'] = 1;
        $map['a.end_time'] = ['>',$time];

        $model = new UserGuard();
        $rows = $model->getRows($map);

        api_return(1,'获取成功',$rows);

    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 获取贵族排行榜
     */
    public function noble()
    {

        $time = cache('nobleTime');
        $map = [];

        if (time()+30 > $time){
            $time = time() + 30;
            cache('nobleTime',$time);
        }

        $map['e.noble_id']   = ['>',0];
        $map['e.noble_time'] = ['>',$time];

        $model = new Users();

        $rows = $model->getNoble($map);

        api_return(1,'获取成功',$rows);

    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 创建|修改房间
     */
    public function createRoom()
    {

        $data = request()->only(['room_name','img','cid','is_lock','password','topic','id','is_close'],'post');

        if (is_numeric($data['id'])){
            $room_id = $data['id'];
        }else{

            if (empty($data['img'])){
                $data['img'] = self::getExtend('default_room_bg');
            }

//            $extra = self::userExtra('noble_id,user_id,noble_time',$this->user_id);
//            $noble_id = self::checkNoble($extra);

//            if ($noble_id == 0) api_return(0,'非贵族不能创建房间');

            $map['user_id'] = $this->user_id;
//            $map['status']  = 1;
            $room_id = Db::name('room')->where($map)->value('room_id');

            if ($room_id){
                if ($this->roomInfo($room_id,'status') == 0){
                    api_return(0,'您的房间已被封禁,请联系管理员处理!');
                }
                api_return(0,'您已创建了房间,不能重复创建');
            }

            $data['type'] = 1;
            $data['user_id'] = $this->user_id;
            $data['bg_id'] = Db::name('room_background')->where('status',1)->order('sort')->value('bg_id');
        }

        $model = new \app\common\logic\Room();

        $result = $model->saveChange($data);

        if ($result !== false){
            if (!is_numeric($data['id'])){
                $room_id = $result;
                //发送系统消息给在线用户告知创建了房间
//                $where['a.follow_user']   = $this->user_id;
//                $where['a.status']        = 1;
//                $where['e.online_status'] = 1;
//                $model = new UserFollow();
//                $rows  = $model->getOnline($where);
//                if (!empty($rows)){
//                    $nick_name = $this->userInfo('nick_name');
//                    $content = sprintf('%s创建了房间[%s],快来围观吧!',$nick_name,$data['room_name']);
//                    $extra['type'] = 'createRoom';
//                    $extra['data'] = $room_id;
//                    foreach ($rows as $k => $v){
//                        $uid[] = hashid($v['user_id']);
//                    }
//                    self::sendUsrMsg('system',$uid,$content,$extra);
//                }

            }else{ //修改房间通知到房间内部修改了内容
                $room = Db::name('room')
                    ->alias('a')
//                    ->join('room_background b','b.bg_id = a.bg_id','LEFT')
                    ->where('a.room_id',$data['id'])
                    ->field('a.is_vague,a.topic,a. bg_img,a.room_name,a.is_lock,a.password,a.img')
                    ->find();
                $this->sendRoomMsg($data['id'],'changeRoom',$room);
            }
            api_return(1,'操作成功',['room_id'=> $room_id]);
        }
        api_return(0,$model->getError());

    }
    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 自己创建房间分类获取
     */
    public function roomCate()
    {
        $rows = Db::name('room_category')->where('status',1)->field('cid,cate_name')->select();
        api_return(1,'获取成功',$rows);
    }



    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 已创建房间和家族id返回接口
     */
    public function myCircle()
    {
        $map['user_id'] = $this->user_id;
        $map['status']  = 1;

        $rows['room_id'] = Db::name('room')->where($map)->value('room_id')??0;

        $where['group_user'] = $this->user_id;
        $where['type']   = 2;
        $where['status'] = 1;

        $noble = $this->userExtra('noble_id,noble_time,user_id');

        $rows['noble_id'] = self::checkNoble($noble);

        $rows['group_id'] = Db::name('chat_group')->where($where)->value('group_id')??0;

        api_return(1,'获取成功',$rows);


    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 聊天室开关公屏
     */
    public function chat()
    {
        $data = input('post.');
        $powerCode = getPowerCode($this->user_id,$data['room_id']);

        if ($powerCode == 0){
            api_return(0,'权限不足');
        }

        if($data['type'] != 'open' && $data['type'] != 'close'){
            api_return(0,'类型错误');
        }
        cache('chat'.$data['room_id'],$data['type']);
        $this->sendRoomMsg($data['room_id'],$data['type']);
        api_return(1,'操作成功');
    }




    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 房间背景列表
     */
    public function bgList()
    {
        //查询是否有背景修改卡
        $map['user_id'] = $this->user_id;
        $map['type']    = 2;
        $map['key']     = 2;

        $num = Db::name('my_package')->where($map)->value('num')??0;

        $rows['num']   = $num;
        $rows['items'] = RoomBackground::field('bg_id,img,brief')->order('sort')->cache(3)->select();

        api_return(1,'获取成功',$rows);
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 砸蛋抽奖
     */
    public function draw()
    {
        //抽奖次数
        $num = input('post.num');

        $money = bcmul($num,self::getExplain('eggPrice'),2);

        $total = $this->userBalance()['money'];

        if ($total < $money){
            api_return(0,'余额不足,不能抽奖');
        }

        $map['chance'] = ['>',0];
        $map['status'] = 1;
        $rows = Db::name('draw')->where($map)->cache(5)->select();

        if (empty($rows)){
            api_return(0,'当前奖池为空,不能抽奖!');
        }

        $proArr = [];

        $prize = [];

        foreach ($rows as $value){
            $proArr[$value['id']] = $value['chance'];
            $prize[$value['id']] = $value;
        }


        $win = [];

        for ($i = 1;$i <= $num;$i++){
            $id =  DrawService::draw('draw');
            if (isset($win[$id])){
                $win[$id] ++;
            }else{
                $win[$id] = 1;
            }
        }

        $Prizes = [];
        //算出中了哪些奖品
        foreach ($win as $k => $v){
            if ($k == 11){
                continue;
            }

            $item['key']     = $prize[$k]['key'];;
//            $item['user_id'] = $this->user_id;
            $item['type'] = $prize[$k]['type'];
            $item['remark']    = $prize[$k]['remark'];
            $item['num']     = $v;
            $item['name']    = $prize[$k]['name'];


            if ($item['type'] == 1){
                $item['name']  = getGiftName($item['key']);
                $item['img']   = getGiftImg($item['key']);
                $item['price'] = getGiftPrice($item['key']);
            }else{
                $item['name']  = $prize[$k]['name'];
                $item['img']   = $prize[$k]['img'];
                $item['price'] = $prize[$k]['price'];
            }


            $Prizes[] = $item;
        }

        $model = new MyPackage();

        Db::startTrans();
        try{

            //扣除抽奖金额
            $this->moneyDec($money);
            money_detail(2,$this->user_id,'抽奖活动->砸蛋'.$num.'次',$money,'消费');
            //更新背包
            foreach ($Prizes as $k => $v){

                $map = [];
                $map['user_id'] = $this->user_id;
                $map['type'] = $v['type'];
                $map['key']  = $v['key'];
                $has = $model->where($map)->find();

                if ($has){
                    $model->where('p_id',$has['p_id'])->setInc('num',$v['num']);
                }else{
                    $map['num'] = $v['num'];
                    $model->insert($map);
                }

                $map['num'] = $v['num'];
                $map['total'] = $v['price'] * $v['num'];
                $map['price'] = $v['price'];
                $map['create_time'] = time();
                $map['update_time'] = time();
                $map['remark'] = '砸蛋';
                $data = $v;
                $data['nick_name'] = self::staticInfo('nick_name',$this->user_id);
                $data['level'] = self::staticExtra('level',$this->user_id);
                $data['user_id']   = hashid($this->user_id);
                $data['remark'] = $map['remark'];

                if ($data['price'] >= self::getExplain('drawPush')){
                    //推送全服

                    $this->sendRoomMsg('all','activity',$data);

                }else{
                    if (is_numeric(input('room_id'))){
                        $this->sendRoomMsg(input('room_id'),'activity',$data);
                    }
                }

                Db::name('draw_record')->strict(false)->insert($map);

            }
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            api_return(0,$e->getMessage());
        }
        api_return(1,'抽奖完成',$Prizes);
    }

    public function draw_sec()
    {
        //抽奖次数
        $num = input('post.num');

        $money = bcmul($num,self::getExplain('eggPriceSec'),2);

        $total = $this->userBalance()['money'];

        if ($total < $money){
            api_return(0,'余额不足,不能抽奖');
        }

        $map['status'] = 1;
        $map['chance'] = ['>',0];
        $rows = Db::name('draw_sec')->where($map)->cache(5)->select();

        if (empty($rows)){
            api_return(0,'当前奖池为空,不能抽奖!');
        }
        $proArr = [];

        $prize = [];

        foreach ($rows as $value){
            $proArr[$value['id']] = $value['chance'];
            $prize[$value['id']] = $value;
        }

        $win = [];

        for ($i = 1;$i <= $num;$i++){
            $id = DrawService::draw('draw_sec');
            if (isset($win[$id])){
                $win[$id] ++;
            }else{
                $win[$id] = 1;
            }
        }
        $Prizes = [];
        //算出中了哪些奖品
        foreach ($win as $k => $v){
            if ($k == 11){
                continue;
            }
            $item['key']     = $prize[$k]['key'];;
//            $item['user_id'] = $this->user_id;
            $item['type'] = $prize[$k]['type'];
            $item['remark']    = $prize[$k]['remark'];
            $item['num']     = $v;
            $item['name']    = $prize[$k]['name'];


            if ($item['type'] == 1){
                $item['name']  = getGiftName($item['key']);
                $item['img']   = getGiftImg($item['key']);
                $item['price'] = getGiftPrice($item['key']);
            }else{
                $item['name']  = $prize[$k]['name'];
                $item['img']   = $prize[$k]['img'];
                $item['price'] = $prize[$k]['price'];
            }


            $Prizes[] = $item;
        }

        $model = new MyPackage();

        Db::startTrans();
        try{

            //扣除抽奖金额
            $this->moneyDec($money);
            money_detail(2,$this->user_id,'抽奖活动->砸蛋'.$num.'次',$money,'消费');
            //更新背包
            foreach ($Prizes as $k => $v){
                $map = [];
                $map['user_id'] = $this->user_id;
                $map['type'] = $v['type'];
                $map['key']  = $v['key'];
                $has = $model->where($map)->find();
                if ($has){
                    $model->where('p_id',$has['p_id'])->setInc('num',$v['num']);
                }else{
                    $map['num'] = $v['num'];
                    $model->strict(false)->insert($map);
                }

                $map['num'] = $v['num'];
                $map['total'] = $v['price'] * $v['num'];
                $map['price'] = $v['price'];
                $map['create_time'] = time();
                $map['update_time'] = time();
                $map['remark'] = '砸蛋';
                $map['draw_type'] = 2;
                $data = $v;
                $data['nick_name'] = self::staticInfo('nick_name',$this->user_id);
                $data['level'] = self::staticExtra('level',$this->user_id);
                $data['user_id']   = hashid($this->user_id);
                $data['remark'] = $map['remark'];
                if ($data['price'] >= self::getExplain('drawPush')){
                    //推送全服

                    $this->sendRoomMsg('all','activity',$data);

                }else{
                    if (is_numeric(input('room_id'))){
                        $this->sendRoomMsg(input('room_id'),'activity',$data);
                    }
                }

                Db::name('draw_record')->strict(false)->insert($map);

            }
            Db::commit();
        }catch (Exception $e){
            Db::rollback();
            api_return(0,$e->getMessage());
        }
        api_return(1,'抽奖完成',$Prizes);
    }
    /**
     * 中奖记录
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     */
    public function prise()
    {
        $map['u.user_id'] = $this->user_id;
        $map['a.status']  = 1;
        $model = new DrawRecord();
        $rows  = $model->getRecord($map);

        api_return(1,'获取成功',$rows);

    }

    /**
     * 派单房列表
     * @param Request $request
     */
    public function orderRooms(Request $request)
    {
        $map['a.status'] = 1;
//        $map['a.is_order'] = 2;
        $type = input('post.type');
        if (is_numeric($type)){
            $map['a.type'] = $type;
        }else{
            $map['a.type'] = 3;
        }
        $model = new Room();
        $rows = $model->orderRooms($map, 'host_id');
        api_return(1,'获取成功',$rows);
    }

    /**
     * 新秀房列表
     * @param Request $request
     */
    public function rookieRooms(Request $request)
    {
        $map['a.status'] = 1;
        $map['a.is_order'] = 3;
        $type = input('post.type');
        if (is_numeric($type)) $map['a.type'] = $type;
        $model = new Room();
        $rows = $model->orderRooms($map, 'user_id',$this->user_id);
        api_return(1,'获取成功',$rows);
    }

    /**
     * Created by xiaosong
     * E-mail:4155433@gmail.com
     * 房间礼物统计
     */
    public function giftCount()
    {
        $data = input();

        if (!is_numeric($data['room_id'])){
            api_return(0,'房间id错误');
        }
        $map['a.room_id'] = $data['room_id'];

        if ($data['keyword']){
            $map['u.nick_name|uuid'] = ['like','%'.trim($data['keyword']).'%'];
        }

        if (is_numeric($data['startTime'])){
            if (is_numeric($data['endTime'])){
                if ($data['endTime'] < $data['startTime']){
                    api_return(0,'结束日期不能大于开始日期');
                }
                $map['a.create_time'] = ['between time',[$data['startTime'],$data['endTime']]];
            }else{
                $map['a.create_time'] = ['> time',$data['startTime']];
            }
        }elseif (is_numeric($data['endTime'])){
            $map['a.create_time'] = ['<=',$data['endTime']];
        }

        $model = new GiftRecord();

        $rows = $model->roomCount($map);

        api_return(1,'获取成功',$rows);
    }



}